package org.petstore.persistence.impl;

import org.petstore.domain.Product;
import org.petstore.persistence.ProductDAO;
import org.petstore.persistence.util.DBUtil;
import org.petstore.persistence.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class ProductDAOImpl implements ProductDAO {
    private final JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    private static final String GET_PRODUCT_LIST_BY_CATEGORY = "SELECT PRODUCTID, NAME, DESCN as description, CATEGORY as categoryId FROM PRODUCT WHERE CATEGORY = ?";
    private static final String GET_PRODUCT = "SELECT PRODUCTID, NAME, DESCN as description,CATEGORY as categoryId FROM PRODUCT WHERE PRODUCTID = ?";
    private static final String SEARCH_PRODUCT_LIST = "SELECT PRODUCTID, NAME, DESCN as description,CATEGORY as categoryId FROM PRODUCT WHERE LOWER(NAME) LIKE ?";

    /**
     * description 获取productList通过categoryId
     *
     * @param categoryId:
     * @return List<Product>
     * @author huangzhangyan
     * @date 2021/10/31 23:47
     */
    @Override
    public List<Product> getProductListByCategory(String categoryId) {
        List<Product> list;
        try {
            list = template.query(GET_PRODUCT_LIST_BY_CATEGORY, new BeanPropertyRowMapper<>(Product.class), categoryId);
        } catch (DataAccessException e) {
            list = null;
        }
        return list;
    }

    /**
     * description 通过productId返回product
     *
     * @param productId:
     * @return Product
     * @author huangzhangyan
     * @date 2021/10/31 23:48
     */
    @Override
    public Product getProductByProductId(String productId) {
        Product product;
        try {
            product = template.queryForObject(GET_PRODUCT, new BeanPropertyRowMapper<>(Product.class), productId);
        } catch (DataAccessException e) {
            product = null;
        }
        return product;
    }

    /**
     * description 通过关键字查找productList 模糊查找 % 在service层处理
     *
     * @param keywords:
     * @return List<Product>
     * @author huangzhangyan
     * @date 2021/10/31 23:50
     */
    @Override
    public List<Product> searchProductList(String keywords) {
        List<Product> list;
        try {
            list = template.query(SEARCH_PRODUCT_LIST, new BeanPropertyRowMapper<>(Product.class), keywords);
        } catch (DataAccessException e) {
            list = null;
        }
        return list;
    }
}
